class SortController {
    constructor() {
        this.array = [];
        this.delay = 100;
        this.isSorting = false;
        this.generateNewArray(15);
    }

    generateNewArray(size) {
        this.array = Array.from({length: size}, () => 
            Math.floor(Math.random() * 90) + 10);
        this.updateVisualization();
    }

    updateVisualization() {
        const container = document.getElementById('visualization');
        container.innerHTML = '';
        const maxHeight = Math.max(...this.array);
        
        this.array.forEach((value, index) => {
            const bar = document.createElement('div');
            bar.className = 'bar';
            bar.style.height = `${(value / maxHeight) * 90}%`;
            bar.textContent = value;
            container.appendChild(bar);
        });
    }

    async swapElements(i, j) {
        [this.array[i], this.array[j]] = [this.array[j], this.array[i]];
        this.highlightSwap(i, j);
        await new Promise(resolve => setTimeout(resolve, this.delay));
        this.updateVisualization();
    }

    highlightCompare(i, j) {
        const bars = document.getElementsByClassName('bar');
        bars[i].classList.add('active');
        bars[j].classList.add('active');
    }

    highlightSwap(i, j) {
        const bars = document.getElementsByClassName('bar');
        bars[i].classList.add('swapping');
        bars[j].classList.add('swapping');
    }

    resetHighlights() {
        document.querySelectorAll('.bar').forEach(bar => {
            bar.classList.remove('active', 'swapping');
        });
    }

    // 排序算法实现
    async bubbleSort() {
        for (let i = 0; i < this.array.length; i++) {
            for (let j = 0; j < this.array.length - i - 1; j++) {
                if (!this.isSorting) return;
                updateAlgorithmExplanation('bubble', `比较索引 ${j} 和 ${j+1} 的元素`);
                this.highlightCompare(j, j+1);
                await new Promise(resolve => setTimeout(resolve, this.delay/2));
                
                if (this.array[j] > this.array[j+1]) {
                    updateAlgorithmExplanation('bubble', `交换 ${this.array[j]} 和 ${this.array[j+1]}`);
                    await this.swapElements(j, j+1);
                }
                this.resetHighlights();
            }
        }
    }

    async quickSort(start = 0, end = this.array.length - 1) {
        if (start >= end || !this.isSorting) return;
        
        let pivot = start;
        let left = start + 1;
        let right = end;

        while (left <= right) {
            while (left <= end && this.array[left] <= this.array[pivot]) {
                left++;
            }
            while (right > start && this.array[right] >= this.array[pivot]) {
                right--;
            }
            if (left < right) {
                updateAlgorithmExplanation('quick', `交换 ${this.array[left]} 和 ${this.array[right]}`);
                await this.swapElements(left, right);
            }
        }
        updateAlgorithmExplanation('quick', `将基准元素 ${this.array[pivot]} 放到正确位置`);
        await this.swapElements(pivot, right);
        
        updateAlgorithmExplanation('quick', '递归排序左半部分');
        await this.quickSort(start, right - 1);
        updateAlgorithmExplanation('quick', '递归排序右半部分');
        await this.quickSort(right + 1, end);
    }

    async heapSort() {
        const n = this.array.length;
        
        // 构建最大堆
        for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
            await this.heapify(n, i);
        }
        
        // 逐个提取元素
        for (let i = n - 1; i > 0; i--) {
            updateAlgorithmExplanation('heap', `步骤1/3: 当前最大堆顶元素是 ${this.array[0]}`);
            await this.swapElements(0, i);
            updateAlgorithmExplanation('heap', `步骤2/3: 将${this.array[0]}交换到已排序区`);
            updateAlgorithmExplanation('heap', '步骤3/3: 调整剩余元素重建最大堆');
            await this.heapify(i, 0);
        }
    }

    async heapify(n, i) {
        let largest = i;
        const left = 2 * i + 1;
        const right = 2 * i + 2;

        if (left < n && this.array[left] > this.array[largest]) {
            largest = left;
        }
        if (right < n && this.array[right] > this.array[largest]) {
            largest = right;
        }
        if (largest !== i) {
            await this.swapElements(i, largest);
            await this.heapify(n, largest);
        }
    }

    async start(algorithm) {
        if (this.isSorting) return;
        this.isSorting = true;
        
        switch(algorithm) {
            case 'bubble':
                await this.bubbleSort();
                break;
            case 'quick':
                await this.quickSort();
                break;
            case 'heap':
                await this.heapSort();
                break;
        }
        this.isSorting = false;
    }
}

const controller = new SortController();

// 事件处理函数
// 算法说明对象
const algorithmExplanations = {
    bubble: '冒泡排序：通过相邻元素比较交换，将最大元素逐步移动到末尾。时间复杂度O(n²)，稳定排序算法。',
    quick: '快速排序：采用分治策略，选取基准元素将数组分为两部分递归排序。平均时间复杂度O(n log n)，不稳定排序。',
    heap: '堆排序：利用堆数据结构，建立最大堆后不断提取最大元素。时间复杂度O(n log n)，原地排序算法。'
};

// 更新算法说明（带步骤演示）
function updateAlgorithmExplanation(algorithm, step = '') {
    const explanationDiv = document.getElementById('algorithm-explanation');
    let explanation = algorithmExplanations[algorithm];
    
    // 添加步骤说明
    if (step) {
        explanation += `\n\n当前步骤：${step}`;
    }
    
    explanationDiv.style.opacity = '0';
    setTimeout(() => {
        explanationDiv.textContent = explanation;
        explanationDiv.style.opacity = '1';
    }, 300);
}

function startSort() {
    const algorithm = document.getElementById('algorithm').value;
    updateAlgorithmExplanation(algorithm);
    controller.start(algorithm);
}

function resetArray() {
    controller.generateNewArray(15);
}

function updateSpeed(value) {
    controller.delay = 200 - value;
}